﻿angular.module('Caltech').controller('workOrderController', function ($scope, Restangular, ngTableParams, $stateParams, $location) {
    'use strict';

    $scope.customer = { name: '' };

    $scope.getCustomerList = function (nameFitler) {
        return Restangular.all('customer/list').getList({
            name: nameFitler
        });
    };

    $scope.search = function (customer, index) {
        if (typeof (customer) === 'string') {
            $scope.customer = {
                name: customer
            }
        } else if (typeof (customer) === 'object') {
            $scope.customer = customer;
        }

        if ($scope.tableParams) {
            $scope.tableParams.reload();
        } else {
            $scope.tableParams = new ngTableParams({
                page: index || 1,
                count: 10
            }, {
                counts: [],
                getData: function ($defer, params) {
                    var customerId = $scope.customer.id || undefined,
                        customerName = customerId === undefined && $scope.customer.name ? $scope.customer.name : undefined;

                    Restangular.all('workOrder')
                        .getList({
                            page: params.page(),
                            count: params.count(),
                            customerName: customerName,
                            customerId: customerId
                        }).then(function (data) {
                            params.total(data.total);
                            $defer.resolve(data);

                            if (params.page() > 1) {
                                $location.search('pageIndex', params.page());
                            }
                            $location.search('customerName', $scope.customer.name || undefined);
                            $location.search('customerId', $scope.customer.id || undefined);
                        });
                }
            });
        }
    };

    $scope.updateCustomer = function (item) {
        $scope.search({ id: item.id, name: item.name });
    };

    if ($stateParams.customerId || $stateParams.customerName || $stateParams.pageIndex) {
        $scope.search(
            {
                id: $stateParams.customerId,
                name: $stateParams.customerName
            },
            $stateParams.pageIndex);
    } else {
        $scope.search();
    }

});